<template>
  <div class="xmgl" v-loading.fullscreen.lock="loading">
    <navbar :showHeaderIcon="true" />
    <div class="app-container">
      <div class="page-card">
        <div class="page-form">
          <el-form
            ref="form"
            :model="queryParams"
            label-position="left"
            label-width="auto"
          >
            <el-row :gutter="32">
              <el-col :span="8">
                <el-form-item label="年级：">
                  <el-select
                    v-model="queryParams.grade"
                    @change="handleSearch"
                    clearable
                    ><el-option
                      v-for="dict in dict.type.grade"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="时间：">
                  <el-date-picker
                    v-model="time"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    @change="handleSearch"
                    value-format="yyyy-MM-dd"
                    clearable
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="32">
              <el-col :span="8">
                <el-form-item label="类型：">
                  <el-select
                    v-model="queryParams.selectType"
                    @change="handleSearch"
                    clearable
                  >
                    <el-option
                      v-for="dict in xklxlb"
                      :key="dict.id"
                      :label="dict.groupName"
                      :value="dict.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="项目：">
                  <el-input
                    style="width: 350px"
                    v-model="queryParams.examName"
                    placeholder="搜索项目名称或代码"
                    prefix-icon="el-icon-search"
                    @input="handleSearch"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <div class="btn-box">
            <el-button type="danger" @click="ytyxm" v-hasRole="['admin']"
              >已停用项目</el-button
            >
            <el-button
              type="primary"
              @click="editKmVisible = true"
              v-hasRole="['admin']"
              >创建新项目</el-button
            >
            <!-- <el-button type="primary">创建复用考试</el-button> -->
          </div>
        </div>
      </div>

      <div class="list">
        <Empty v-if="!loading && tableData.length == 0" />

        <div class="item" v-for="item in tableData" :key="item.id">
          <div class="item-content">
            <div class="item-title">
              {{ item.examName }}
            </div>
            <div class="item-status-box">
              <div class="item-status type">
                <dict-tag :options="dict.type.type" :value="item.examType" />
              </div>
              <div v-if="item.status == 0" class="item-status">
                状态：未发布
              </div>
              <div v-if="item.status == 1" class="item-status">
                状态：已发布
              </div>
              <div v-if="item.status == 2" class="item-status">
                状态：发布异常
              </div>
            </div>
            <div class="item-info">
              <p>
                <span class="info-item-label">考试时间：</span>
                <span> {{ item.startTime }} - {{ item.endTime }}</span>
                <span class="info-item-label">考试范围：</span>
                <span>
                  {{ selectDictLabel(dict.type.grade, item.grade) }}
                </span>
                <span class="info-item-label">考试模式：</span>
                <span
                  >{{ selectDictLabel(dict.type.mode, item.projectMode) }}
                  {{ item.selectTypeName }}</span
                >
              </p>
            </div>
            <!-- <div class="item-info" :class="{ open: item.open }">
              <p>
                <span class="info-item-label">信息设置：</span>
                <km-tag :option="subjectFilter(item.examSubjectList)"></km-tag>
                <el-link
                  v-if="!item.open"
                  @click="toggleOpen(index)"
                  type="primary"
                  class="item-info-btn"
                >
                  展开</el-link
                >
              </p>
              <p>
                <span class="info-item-label">题卡扫描：</span>
                <span>语文、化学、政治、地理</span>
              </p>
              <p>
                <span class="info-item-label">试卷评阅：</span>
                <span>数学、政治、地理</span>
              </p>
              <p>
                <span class="info-item-label">成绩分析：</span>
                <span>物理、语文、化学、政治、地理</span>
                <el-link
                  v-if="item.open"
                  @click="toggleOpen(index)"
                  type="primary"
                  class="item-info-btn"
                >
                  收起</el-link
                >
              </p>
            </div> -->
          </div>

          <div class="item-button">
            <el-button type="danger" @click="ty(item.id)" v-hasRole="['admin']">
              <!-- <img src="../../assets/images/ty.png" alt="" /> -->
              停用项目
            </el-button>
            <el-button type="primary" @click="ck(item)">
              <!-- <img src="../../assets/images/ksgl.png" alt="" /> -->
              查看项目
            </el-button>
          </div>
        </div>
      </div>
    </div>
    <div class="page-bottom">
      <div class="page-bottom-content">
        <span class="total">共{{ total }}条数据</span>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    <el-dialog
      ref="editDialog"
      class="editKmVisible"
      title="创建新项目"
      :visible.sync="editKmVisible"
      width="520px"
      :before-close="beforeClose"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="rules"
        label-position="left"
        label-width="120px"
      >
        <el-form-item label="项目名称" prop="examName">
          <el-input v-model="editForm.examName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="项目时间" prop="examTime">
          <el-date-picker
            :picker-options="pickerOptions"
            v-model="editForm.examTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="所属年级" prop="grade">
          <el-select v-model="editForm.grade">
            <el-option
              v-for="dict in dict.type.grade"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          /></el-select>
        </el-form-item>
        <el-form-item label="项目类型" prop="examType">
          <el-select v-model="editForm.examType">
            <el-option
              v-for="dict in dict.type.type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目模式" prop="projectMode">
          <el-select v-model="editForm.projectMode">
            <el-option
              v-for="dict in dict.type.mode"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          /></el-select>
        </el-form-item>
        <el-form-item label="选科类型" prop="selectType">
          <el-select v-model="editForm.selectType">
            <el-option
              v-for="dict in xklxlb"
              :key="dict.id"
              :label="dict.groupName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分数线(多选)" prop="scoreBarList">
          <el-select v-model="editForm.scoreBarList" multiple>
            <el-option
              v-for="dict in scoreBar"
              :key="dict"
              :label="dict"
              :value="dict"
          /></el-select>
        </el-form-item>
        <!-- <el-form-item label="选择考试" prop="examSubjectList">
          <el-select v-model="editForm.examSubjectList" multiple>
            <el-option
              v-for="dict in xklb"
              :key="dict.subjectId"
              :label="dict.subjectName"
              :value="dict.subjectId"
          /></el-select>
        </el-form-item> -->
        <el-form-item label="总分" prop="fullMark">
          <el-input v-model="editForm.fullMark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">返 回</el-button>
        <el-button type="primary" @click="editSubmit">保 存</el-button>
      </div>
    </el-dialog>

    <el-dialog
      ref="tyDialog"
      class="tyDialog"
      title="已停用项目"
      :visible.sync="tyVisible"
      width="1000px"
    >
      <p class="ty-tips">
        此列表仅展示已停用3个月内的考试，超过后考试无法启用。
      </p>
      <el-table stripe border :data="tyTableData">
        <el-table-column
          label="项目类型"
          align="center"
          prop="schoolName"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ selectDictLabel(dict.type.mode, scope.row.projectMode) }}
          </template>
        </el-table-column>
        <el-table-column
          label="项目范围"
          align="center"
          prop="schoolName"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ selectDictLabel(dict.type.grade, scope.row.grade) }}
          </template>
        </el-table-column>
        <el-table-column
          label="项目名称"
          align="center"
          prop="examName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="项目时间"
          align="center"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ scope.row.startTime }} - {{ scope.row.endTime }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="$auth.hasRole('admin')"
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="80"
        >
          <template slot-scope="scope">
            <el-link type="primary" @click="qy(scope.row)">启用</el-link>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        class="m-top"
        v-show="tyTotal > 0"
        :total="tyTotal"
        :page.sync="tyPageNum"
        :limit.sync="tyPageSize"
        @pagination="getTyList"
        layout="prev, pager, next, jumper,total"
      />
    </el-dialog>
  </div>
</template>

<script>
import { listDept } from "@/api/system/dept";
import { debounce } from "lodash";
import { grouplist } from "@/api/jcgl/xkgl";
import {
  exammainlist,
  exammainlistbyteacher,
  exammainAdd,
  exammainEdit,
} from "@/api/xmgl";
import { subjectlistselect } from "@/api/common";
import { Navbar } from "@/layout/components";
import { examPermissionsData } from "@/utils/examPermissions.js";
export default {
  name: "Project_xmgl",
  components: {
    Navbar,
  },
  dicts: ["grade", "type", "mode"],
  data() {
    return {
      req: null,

      loading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        schoolId: this.$auth.hasRole("admin")
          ? ""
          : this.$store.state.user.deptId,
      },

      open: false,

      total: 0,
      tableData: [],

      editKmVisible: false,
      scoreBar: [
        "清北线",
        "985线",
        "211线",
        "特控(一本)线",
        "本科(二本)线",
        "专科线",
      ],
      editForm: {
        examName: "",
        examTime: null,
        grade: "",
        examType: "",
        projectMode: "",
        selectType: "",
        examSubjectList: [],
        scoreBarList: [],
        fullMark:null,
      },
      rules: {
        examName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const regex = /^[\u4e00-\u9fa5a-zA-Z0-9\s]+$/;
              if (!regex.test(value)) {
                callback(new Error("项目名称不允许输入符号"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        examTime: [
          { required: true, message: "项目时间不能为空", trigger: "change" },
        ],
        grade: [
          { required: true, message: "所属年级不能为空", trigger: "change" },
        ],
        examType: [
          { required: true, message: "项目类型不能为空", trigger: "blur" },
        ],
        projectMode: [
          { required: true, message: "项目模式不能为空", trigger: "change" },
        ],
        selectType: [
          { required: true, message: "选科类型不能为空", trigger: "change" },
        ],
        examSubjectList: [
          { required: true, message: "考试不能为空", trigger: "change" },
        ],
        scoreBarList: [
          { required: true, message: "分数线不能为空", trigger: "change" },
        ],
        fullMark: [
          { required: true, message: "总分不能为空", trigger: "change" },
        ],
      },

      xklxlb: [],
      qbxklb: [],
      dqList: [],

      tyVisible: false,
      tyTableData: [],
      tyPageNum: 1,
      tyPageSize: 15,
      tyTotal: 0,

      time: "",

      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 86400000;
        },
      },
    };
  },
  computed: {
    xklb() {
      let xklb = [];
      if (this.editForm.selectType) {
        let obj = this.xklxlb.filter((item) => {
          return this.editForm.selectType == item.id;
        })[0];
        console.info(obj, "objsssss");
        let examSubjects = obj.examSubjects ? obj.examSubjects.split(",") : [];
        let basicChooseSubject;
        if (obj.basicChooseSubject) {
          basicChooseSubject = obj.basicChooseSubject.map((item) => {
            return item.selectSubjectIds.split(",");
          });
          basicChooseSubject = basicChooseSubject.reduce((acc, curr) => {
            return acc.concat(curr);
          }, []);
          examSubjects = examSubjects.concat(basicChooseSubject);
        }

        this.qbxklb.map((item) => {
          if (examSubjects.indexOf(item.subjectId.toString()) != -1) {
            xklb.push(item);
          }
        });
      }

      return xklb;
    },
  },
  created() {
    this.$store.dispatch("setActiceHeaderSidebar", "项目管理");

    grouplist({ pageNum: 1, pageSize: 9999 }).then((res) => {
      this.xklxlb = res.rows;
    });
    subjectlistselect("-1").then((res) => {
      this.qbxklb = res.data;
    });

    if (this.$auth.hasRole("admin")) {
      this.req = exammainlist;
      listDept({ pageNum: 1, pageSize: 9999 }).then((response) => {
        let deptList = this.handleTree(response.data, "deptId");
        // 过滤出二级地区列表
        let dqList = deptList.filter((item) => {
          return item.children && item.children.length > 0;
        });
        dqList.map((item) => {
          item.children.map((v) => {
            delete v.children;
          });
        });
        this.dqList = dqList;
      });
    } else {
      this.req = exammainlistbyteacher;
    }
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      this.tableData = [];
      if (this.time) {
        this.queryParams.startTime = this.time[0];
        this.queryParams.endTime = this.time[1];
      } else {
        this.queryParams.startTime = "";
        this.queryParams.endTime = "";
      }

      this.req({ ...this.queryParams, stopped: 0 })
        .then((response) => {
          this.tableData = response.rows;
          this.total = response.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    getTyList() {
      this.loading = true;
      exammainlist({
        pageNum: this.tyPageNum,
        pageSize: this.tyPageSize,
        stopped: 1,
      })
        .then((response) => {
          this.tyTableData = response.rows;
          this.tyTotal = response.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    ytyxm() {
      this.tyPageNum = 1;
      this.getTyList();
      this.tyVisible = true;
    },

    toggleOpen(index) {
      this.$set(this.tableData[index], "open", !this.tableData[index].open);
    },

    debouncedSearch: debounce(function () {
      this.queryParams.pageNum = 1;
      this.getList();
    }, 500),

    beforeClose(done) {
      this.editForm = {
        examName: "",
        examTime: null,
        grade: "",
        examType: "",
        projectMode: "",
        selectType: "",
        examSubjectList: [],
        scoreBarlist: [],
        fullMark:null,
      };
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate();
        done();
      });
    },
    handleClose() {
      this.beforeClose(() => {
        this.editKmVisible = false;
      });
    },

    editSubmit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          let req = exammainAdd;
          let data = {
            ...this.editForm,
            projectType: this.editForm.examType,
          };

          data.startTime = data.examTime[0];
          data.endTime = data.examTime[1];
          data.examSubjectList = this.xklb.map((item) => {
            return {
              subjectId: item.subjectId,
              subjectName: item.subjectName,
            };
          });

          req(data)
            .then((res) => {
              this.$modal.msgSuccess("操作成功");
              this.handleClose();
              this.getList();
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },

    subjectFilter(arr) {
      return arr.map((item) => {
        return item.subjectName;
      });
    },

    handleSearch() {
      this.debouncedSearch();
    },

    ck(item) {
      this.$store.dispatch("setXmxx", item).then((res) => {
        // if (this.$route.query.redirect) {
        //   this.$router.push(this.$route.query.redirect);
        // } else {
        if (this.$auth.hasRole("admin")) {
          this.$router.push({ name: "Project_ksgl" });
        } else {
          const isPush = () => {
            for (let key in examPermissionsData) {
              if (examPermissionsData[key].path) {
                for (
                  let i = 0, len = examPermissionsData[key].value.length;
                  i < len;
                  i++
                ) {
                  let item = examPermissionsData[key].value[i];
                  if (this.$auth.hasExamPermi(item)) {
                    return examPermissionsData[key].path;
                  }
                }
              }
            }

            return "";
          };

          const path = isPush();
          if (path) {
            this.$router.push(path);
          } else {
            this.$modal.alertError("您的账号没有任何项目管理权限");
          }
        }
        // }
      });
    },
    ty(id) {
      this.$modal.confirm("请确认进行停用操作").then(() => {
        exammainEdit({ id: id, stopped: 1 }).then((res) => {
          this.$modal.msgSuccess("操作成功");
          this.getList();
        });
      });
    },
    qy(item) {
      exammainEdit({ id: item.id, stopped: 0 }).then((res) => {
        this.$modal.msgSuccess("操作成功");
        this.getTyList();
        this.getList();
        this.ck(item);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.editKmVisible {
  .el-input,
  .el-select {
    width: 350px;
  }
}
.app-container {
  .page-card {
    width: 1200px;
    margin-left: auto;
    margin-right: auto;
  }
  .page-form {
    padding: 0;
    justify-content: space-between;
    flex-wrap: wrap;
    .el-form {
      width: 850px;
      .el-row + .el-row {
        margin-top: 14px;
      }
    }
  }

  .list {
    width: 1200px;
    margin-left: auto;
    margin-right: auto;
    margin-top: 20px;
    padding-bottom: 70px;
    .item {
      & + .item {
        margin-top: 20px;
      }
      padding: 24px;
      background: #ffffff;
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;

      .item-title {
        font-size: 20px;
        color: #2a303b;
        line-height: 24px;
        font-weight: bold;
      }

      .item-status-box {
        display: flex;
        margin-top: 14px;
        .item-status {
          padding: 6px 10px;
          border-radius: 12px;
          border: 1px solid #288f41;
          background: #288f410a;
          font-size: 12px;
          line-height: 12px;
          color: #288f41;
          margin-right: 10px;

          &.type {
            background: #1a48db0a;
            color: #1a48db;
            border-color: #1a48db;
          }
        }
      }

      .item-info {
        margin-top: 8px;
        height: 22px;
        overflow: hidden;
        font-size: 14px;
        line-height: 22px;
        position: relative;
        padding-right: 48px;

        &.open {
          height: auto;
        }

        p {
          display: flex;
          align-items: center;
          & + p {
            margin-top: 8px;
          }
          margin: 0;
          .item-info-btn {
            margin-left: 6px;
          }
          .info-item-label {
            color: #5b6371;
          }
          span + .info-item-label {
            margin-left: 24px;
          }
        }
      }
    }
  }
}
.page-bottom {
  width: 100vw;
  background: #ffffff;
  box-shadow: 0 4px 16px 0 #5572921a;
  height: 50px;
  justify-content: center;
  position: fixed;
  bottom: 0;
  left: 0;

  .page-bottom-content {
    width: 1200px;
    display: flex;
    justify-content: space-between;
    align-content: center;

    .total {
      font-size: 14px;
      line-height: 32px;
    }
    .pagination-container {
      margin: 0;
    }
  }
}
</style>

<style lang="scss">
.xmgl {
  .page-form {
    .el-form-item {
      margin-bottom: 0;
      .el-input,
      .el-select {
        width: 100%;
        margin: 0;
      }
    }
  }
}
.ty-tips {
  margin-top: 0;
  color: #f56c6c;
}
.tyDialog .el-pagination__total {
  margin-left: 20px;
  line-height: 30px;
}
</style>
